#!/usr/bin/python

from numpy import *


def main():
    infile = open('data')

    # read data

    line = infile.readline()
    numVec = int(line[1:])

    line = infile.readline()
    numFeat = int(line[1:])

    data = zeros((numVec, numFeat))
    ys = zeros(numVec)

    for i in range(0, numVec):
        line = infile.readline()
        tok = line.split()
        ys[i] = float(tok[0])
        for j in range(0, numFeat):
            label_value = tok[j+1].split(':')
            data[i][j] = float(label_value[1])

    infile.close()

    # compute

    yAvg = mean(ys)
    yStd = std(ys)
    fAvg = mean(data, 0)
    fStd = std(data, 0)

    # write normalized data

    of = open('data_norm', 'wb')

    of.write('# ' + str(numVec) + '\n')
    of.write('# ' + str(numFeat) + '\n')
    for i in range(0, numVec):
        out_string = '%f' % ((ys[i]-yAvg) / yStd)
        for j in range(0, numFeat):
            out_string = (out_string +
                          ' %d:%f' % (j+1, (data[i][j]-fAvg[j])/fStd[j]))
        out_string = out_string + '\n'
        of.write(out_string)
    of.close()

    # write normalizing constants

    of = open('norm_const', 'wb')
    of.write('# ' + str(numVec) + '\n')
    of.write('# ' + str(numFeat) + '\n')

    out_string = '%f,%f' % (yAvg, yStd)
    for j in range(0, numFeat):
        out_string = (out_string +
                      ' %d:%f,%f' % (j+1, fAvg[j], fStd[j]))
    out_string = out_string + '\n'
    of.write(out_string)

    of.close()

if __name__ == "__main__":
    main()
